$(function(){

	var buttonId = $("#buttonId").val();
	var column = "";
	if(buttonId == 'btnGroup0'){
        $("#amount").remove();
        $("#fee").remove();
		$("#receiveAmount").removeClass("hidden");
        $("#leftAmount").removeClass("hidden");
        column = [
            {
                render : function(data,type, row, meta) {
                    return '<a href="'+contextpath+'cOrder/detail/'+row["financeOrderNo"]+'">'+row["financeOrderNo"]+'</a>';
                }
            },
            { "data": "createTime" },
            {
                render : function(data,type, row, meta) {
                    return '<a href="'+contextpath+'customer/detail/'+row["customerId"]+'">'+row["customerName"]+'</a>';
                }
            },
            {
                render : function(data, type, row, meta) {
                    var context = row.distributorShopName;
                    if(context){
                        context += '(' + row.distributorName + ')';
                    }else{
                        context = row.distributorName;
                    }

                    return '<a style="color:red" href="'+contextpath+'customer/detail/'+row["distributorId"]+'">'+context+'</a>';

                    // return '<span style="color:red">' + context + '</span>';
                }
            },
            /*{ "data": "distributorRebate" },
            { "data": "amount" },
            { "data": "receivedAmount"},
            {
                render : function(data, type, row, meta) {
                    return '<span style="color:red">' + row.leftAmount + '</span>';
                }
            },
            { "data": "feeAmount"},*/
            { "data": "receivedAmount"},
            {
                render : function(data, type, row, meta) {
                    return '<span style="color:red">' + row.leftAmount + '</span>';
                }
            },
            {
                render : function(data, type, row, meta) {
                    var productNameAndCount = (row.productNameAndCount && row.productNameAndCount.length > 50) ? (row.productNameAndCount.substring(0, 10) + "....") : row.productNameAndCount;
                    return "<span class='initTip' style='z-index:100;' data-toggle='tooltip' title='" + row.productNameAndCount + "'>" + productNameAndCount + "</span>"
                }
            },
            {
                render : function(data, type, row, meta) {
                    if(buttonId){
                        return $("#" + buttonId).html();
                    }else{
                        return '';
                    }

                }
            }
        ];
	} else if(buttonId == 'btnGroup2' || !buttonId){
        $("#amount").removeClass("hidden");
        $("#fee").removeClass("hidden");
        $("#receiveAmount").removeClass("hidden");
        $("#leftAmount").removeClass("hidden");
        column = [
            {
                render : function(data,type, row, meta) {
                    return '<a href="'+contextpath+'cOrder/detail/'+row["financeOrderNo"]+'">'+row["financeOrderNo"]+'</a>';
                }
            },
            { "data": "createTime" },
            {
                render : function(data,type, row, meta) {
                    return '<a href="'+contextpath+'customer/detail/'+row["customerId"]+'">'+row["customerName"]+'</a>';
                }
            },
            {
                render : function(data, type, row, meta) {
                    var context = row.distributorShopName;
                    if(context){
                        context += '(' + row.distributorName + ')';
                    }else{
                        context = row.distributorName;
                    }

                    return '<a style="color:red" href="'+contextpath+'customer/detail/'+row["distributorId"]+'">'+context+'</a>';

                    // return '<span style="color:red">' + context + '</span>';
                }
            },
            { "data": "amount" },
            /*{ "data": "distributorRebate" },
            { "data": "amount" },
            { "data": "receivedAmount"},
            {
                render : function(data, type, row, meta) {
                    return '<span style="color:red">' + row.leftAmount + '</span>';
                }
            },
            { "data": "feeAmount"},*/
            { "data": "receivedAmount"},
            {
                render : function(data, type, row, meta) {
                    return '<span style="color:red">' + row.leftAmount + '</span>';
                }
            },
            { "data": "feeAmount"},
            {
                render : function(data, type, row, meta) {
                    var productNameAndCount = (row.productNameAndCount && row.productNameAndCount.length > 50) ? (row.productNameAndCount.substring(0, 10) + "....") : row.productNameAndCount;
                    return "<span class='initTip' style='z-index:100;' data-toggle='tooltip' title='" + row.productNameAndCount + "'>" + productNameAndCount + "</span>"
                }
            },
            {
                render : function(data, type, row, meta) {
                    if(buttonId){
                        return $("#" + buttonId).html();
                    }else{
                        return '';
                    }

                }
            }
        ];
    } else{
        $("#receiveAmount").remove();
        $("#leftAmount").remove();
        $("#amount").remove();
        $("#fee").remove();
        column = [
            {
                render : function(data,type, row, meta) {
                    return '<a href="'+contextpath+'cOrder/detail/'+row["financeOrderNo"]+'">'+row["financeOrderNo"]+'</a>';
                }
            },
            { "data": "createTime" },
            {
                render : function(data,type, row, meta) {
                    return '<a href="'+contextpath+'customer/detail/'+row["customerId"]+'">'+row["customerName"]+'</a>';
                }
            },
            {
                render : function(data, type, row, meta) {
                    var context = row.distributorShopName;
                    if(context){
                        context += '(' + row.distributorName + ')';
                    }else{
                        context = row.distributorName;
                    }

                    return '<a style="color:red" href="'+contextpath+'customer/detail/'+row["distributorId"]+'">'+context+'</a>';

                    // return '<span style="color:red">' + context + '</span>';
                }
            },
            /*{ "data": "distributorRebate" },
            { "data": "amount" },
            { "data": "receivedAmount"},
            {
                render : function(data, type, row, meta) {
                    return '<span style="color:red">' + row.leftAmount + '</span>';
                }
            },
            { "data": "feeAmount"},*/
            {
                render : function(data, type, row, meta) {
                    var productNameAndCount = (row.productNameAndCount && row.productNameAndCount.length > 50) ? (row.productNameAndCount.substring(0, 49) + "....") : row.productNameAndCount;
                    return "<span class='initTip' style='z-index:100;' data-toggle='tooltip' title='" + row.productNameAndCount + "'>" + productNameAndCount + "</span>"
                }
            },
            {
                render : function(data, type, row, meta) {
                    if(buttonId){
                        return $("#" + buttonId).html();
                    }else{
                        return '';
                    }

                }
            }
        ];
    }
	$('.datatable-basic').DataTable({
		"scrollX": '300px', //支持垂直滚动
		 "ajax" : {
			"url" : contextpath + "cOrder/list",
			"data" : function(d) {
	            var query = $("#query").serializeObject();
	            query["size"] = d.length;
	            query["page"] = (d.start/d.length);
				return query;
			},
			"dataFilter": function(data){
	            var json = jQuery.parseJSON( data );
	            json.recordsTotal = json.totalElements;
	            json.recordsFiltered = json.totalElements;
	            json.data = json.content;
	 
	            return JSON.stringify( json );
	        }
		 },
		 "columns": column,
	     "drawCallback": function( settings ) {
	    	 
	    	 $(".btn-edit").click(function(){
	    		 var row = $('.datatable-basic').DataTable().row($(this).closest("tr")).data();
	    		 window.location.href = contextpath + "/cOrder/editOrder?orderId=" + row.id;
	    	 });
	    	 
	    	 $(".btn-add-payment").click(function(){
	    		 var row = $('.datatable-basic').DataTable().row($(this).closest("tr")).data();
	    		 $("input[name='orderId']").val(row.id);
	    	 });
	    	 
	    	 $(".btn-payment").click(function(){
	    		 var row = $('.datatable-basic').DataTable().row($(this).closest("tr")).data();
	    		 window.location.href = contextpath + "/cOrderPayment?orderId=" + row.id + "&name=" + row.customerName + "(" + row.distributorName + ")";
	    	 });
	    	 
	    	 $(".btn-operation").click(function(){
	    		 var row = $('.datatable-basic').DataTable().row($(this).closest("tr")).data();
	    		 window.location.href = contextpath + "/customerOperation?orderId=" + row.id;
	    	 });
	    	 
	    	 $(".btn-balance").click(function(){
	    			var row = $('.datatable-basic').DataTable().row($(this).closest("tr")).data();
	    			swal({
	    				title : "结算订单",
	    				text : "确定要结算此订单(总金额：" + row.amount + ", 渠道商提成:" + row.distributorRebate + ")",
	    				type : "warning",
	    				showCancelButton : true,
	    				confirmButtonColor : "#DD6B55",
	    				confirmButtonText : "确定",
	    				cancelButtonText: "取消",
	    				closeOnConfirm : false
	    			},function() {
	    				$.get(contextpath + "cOrder/balance/" + row.id, function(d){
	    					$('.datatable-basic').DataTable().draw();
	    					swal("结算订单成功","", "success");
	    				})
	    			});
	    		});
	    	 
		    	 $(".btn-del").click(function(){
		 			var row = $('.datatable-basic').DataTable().row($(this).closest("tr")).data();
		 			swal({
		 				title : "删除",
		 				text : "确定要删除此订单?",
		 				type : "warning",
		 				showCancelButton : true,
		 				confirmButtonColor : "#DD6B55",
		 				confirmButtonText : "确定",
		 				cancelButtonText: "取消",
		 				closeOnConfirm : false
		 			},function() {
		 				$.get(contextpath + "cOrder/delete/" + row.id, function(d){
		 					$('.datatable-basic').DataTable().draw();
		 					swal("删除订单成功","", "success");
		 				})
		 			});
		 		});
		    	 
		    	 /*$(".initTip").tooltip({
		    	      position: {
		    	        my: "left top",
		    	        at: "left bottom"
		    	      },
		    	      open: function( event, ui ) {
		    	        ui.tooltip.animate({ top: ui.tooltip.position().top + 10 }, "fast" );
		    	      }
		    	 });*/
	      }
	});
	
	$("#submit").click(function(){
		$('.datatable-basic').DataTable().draw();
	});
	
	$("#orderFileInput").fileinput('destroy');
	$("#orderFileInput").fileinput({
		language: 'zh',
		uploadClass: 'btn btn-success',
		showPreview : false,
		uploadUrl: contextpath +  "cOrder/import"
    });
	
	// Setup all runtimes
	 var option = {
       url: contextpath+'cOrder/import',
       chunk_size: 0,
       filters: {
           max_file_size: '10MB',
           mime_types: [{
               title: "excel文件",
               extensions: "xls,xlsx"
           }],
           prevent_duplicates : true
       },
       init:{
       	UploadComplete: function(up, files) {
       		$("#continue").click(function(){
       			$("#uploadinfo").hide();
       			$("#info").show();
       			$(".file-uploader").pluploadQueue(option);
       		});
           },
           FileUploaded : function(uploader,file,respnse){
           		$("#uploadinfo").html("文件" + file.name + " 导入成功. <a class='text-danger' id='continue'>点击此处</a>继续上传");
           },
           Error:function(uploader, errObject){
           	   $("#uploadinfo").html("文件导入失败. <a class='text-danger' id='continue'>点击此处</a>继续上传<div><div>错误信息:" + JSON.parse(errObject.response).message + "</div>");
           },
           UploadFile:function(uploader,file){
           	$("#info").hide();
           	$("#uploadinfo").show();
           	$("#uploadinfo").text("开始上传文件" + file.name);
           }
       }
   }
	 
   $(".file-uploader").pluploadQueue(option);
	
	/* $('#beginDate').daterangepicker({
			"autoApply" : true,
			"singleDatePicker": true,
			"locale" : {
				format : 'YYYYMMDD'
			}
		});	 
	 
	 $('#endDate').daterangepicker({
			"autoApply" : true,
			"singleDatePicker": true,
			"locale" : {
				format : 'YYYYMMDD'
			}
		});	 */
	 
	 $('#beginDate').daterangepicker(
			  { 
				  "singleDatePicker": true,
			    locale:{
			    	format: 'YYYY-MM-DD',
		            applyLabel: '确认',
		            cancelLabel: '取消',
		            fromLabel: '从',
		            toLabel: '到',
		            customRangeLabel: '选择时间',
		            daysOfWeek:["日","一","二","三","四","五","六"],
		            monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
		        }
			  }
			);
	 $('#beginDate').val("");
	 
	 
	 $('#endDate').daterangepicker(
			  { 
				  "singleDatePicker": true,
			    locale:{
			    	format: 'YYYY-MM-DD',
		            applyLabel: '确认',
		            cancelLabel: '取消',
		            fromLabel: '从',
		            toLabel: '到',
		            customRangeLabel: '选择时间',
		            daysOfWeek:["日","一","二","三","四","五","六"],
		            monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
		        }
			  }
			);
	 $('#endDate').val("");
	 
	 $("#export").click(function(){
		 var obj = $("#query").serializeObject();
		 
		 var param = "";
		 for(var i in obj){
			 param += i + "=" + obj[i] + "&"
		 }
		 $("#export").attr("href", contextpath+"cOrder/export?" + param); 
	 });
	 
	 $('select').select2({
		    minimumResultsForSearch: Infinity
		});	
	 
	 $("#addOrder").click(function(){
		 window.location=contextpath + "cOrder/addOrder";
	 });
});

